#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime
from controller.todolistController import TodolistController
from models.todolistModel import Todolist
from app import db
from utils.response_code import RET, error_map_EN
from utils.loggings import loggings
import math
from utils import commons


class TodolistService(TodolistController):

    # 列表事项添加
    @classmethod
    def add_list(cls, **kwargs):
        try:
            from utils.generate_id import GenerateID
            AutoID = GenerateID.create_id_by_autoID()
        except Exception as e:
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': "数据库连接异常,生成ID错误"}}
        try:
            model = Todolist(
                AutoID=int(AutoID),
                Title=kwargs.get('Title'),
                UserID=kwargs.get('UserID'),
            )
            db.session.add(model)
            db.session.commit()
            results = {
                'add_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                'AutoID': model.AutoID,

            }
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'data': results}

        except Exception as e:
            db.session.rollback()
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()

    # 列表的模糊查询
    @classmethod
    def fuzzy_query(cls, **kwargs):
        try:
            filter_list = [cls.IsDelete == 0]
            if kwargs.get('Title'):
                filter_list.append(cls.Title.like("%" + kwargs.get("Title") + "%"))
            if kwargs.get('UserID') is not None:
                filter_list.append(cls.UserID == kwargs.get('UserID'))

            page = int(kwargs.get('Page', 1))
            size = int(kwargs.get('Size', 10))

            todolist_info = db.session.query(cls).filter(*filter_list)

            count = todolist_info.count()
            pages = math.ceil(count / size)
            todolist_info = todolist_info.limit(size).offset((page - 1) * size).all()

            results = commons.query_to_dict(todolist_info)
            return {'code': RET.OK, 'message': error_map_EN[RET.OK], 'totalCount': count, 'totalPage': pages,
                    'data': results}

        except Exception as e:
            loggings.exception(1, e)
            return {'code': RET.DBERR, 'message': error_map_EN[RET.DBERR], 'data': {'error': str(e)}}
        finally:
            db.session.close()
